package cn.sharp.bbs.service.impl;

import cn.sharp.bbs.service.CacheService;
import cn.sharp.bbs.service.SSEService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 'server send event' service
 * @author zhao yu
 */
@Service
@Transactional
public class SSEServiceImpl implements SSEService {

    @Resource
    private CacheService cacheService;

    @Override
    public void push(Long id, Integer type) {
        SseEmitter sseEmitter = cacheService.findMessSseEmitter(id);
        if (sseEmitter != null) {
            try {
                sseEmitter.send(type);
            } catch (IOException e) {
                push(id, type);
            }
        }
    }
}
